package airhockey.spel;

import android.graphics.Canvas;
import android.view.SurfaceHolder;

public class AirhockeyThread extends Thread {
	private long time;
	private final int fps = 60;
	private boolean toRun = false;
	
	private AirhockeySpeelveld airhockeySpeelveld;
	private SurfaceHolder surfaceHolder;
	
	public AirhockeyThread(AirhockeySpeelveld speelveld) {
		airhockeySpeelveld = speelveld;
		surfaceHolder = airhockeySpeelveld.getHolder();
	}

	public void setRunning(boolean run) {
		toRun = run;
	}
	
	@Override
	//running the game loop
	public void run() {
	    Canvas canvas;
	    
	    while (toRun) {
	        long cTime = System.currentTimeMillis();
	        if ((cTime - time) <= (1000 / fps)) {
	            canvas = null;
	            try {
	                canvas = surfaceHolder.lockCanvas(null);
	                //update movements
	                airhockeySpeelveld.updatePhysicsPuk();
	                airhockeySpeelveld.onDraw(canvas);
	            } finally {
	                if (canvas != null) {
	                    surfaceHolder.unlockCanvasAndPost(canvas);
	                }
	            }
	        }
	        time = cTime;
	    }
	}
}
